package com.hybrid.view;

import java.lang.ref.WeakReference;
import java.lang.reflect.Field;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

/**
 * 在此写用途
 *
 * @author: zhiwei
 * @date: 2017-10-09 22:13
 * @version: 9.1.0
 */
public class PopupWindowController {
    private Context mContext;
    private View mView;

    private PopupWindow mPopupWindow;
    private FrameLayout popupViewGroup;
    private LinearLayout popupLayout;
    private Animation mAnimation;

    public PopupWindowController(Context context, View view, String[] tags, OnClickListener listener) {
        this(context, view, null, tags, listener);
    }

    public PopupWindowController(Context context, View view, String title, String[] tags, OnClickListener listener) {
        mContext = context;
        mView = view;

        initButtons(title, tags, listener);
        initPopupWindow();
        mAnimation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0, Animation.RELATIVE_TO_PARENT, 0, Animation.RELATIVE_TO_SELF,
            1, Animation.RELATIVE_TO_SELF, 0);
        mAnimation.setDuration(250);
    }

    public void show() {
        try{
            mPopupWindow.showAtLocation(mView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
            popupLayout.startAnimation(mAnimation);
            mPopupWindow.update();
        }catch(Exception e){
            e.printStackTrace();
        }

    }

    public void hide() {
        mPopupWindow.dismiss();
    }

    private void initPopupWindow() {
        mPopupWindow = new PopupWindow(mContext);
        mPopupWindow.setContentView(popupViewGroup);
        mPopupWindow.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
        mPopupWindow.setHeight(LinearLayout.LayoutParams.MATCH_PARENT);
        mPopupWindow.setFocusable(true);
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setBackgroundDrawable(new ColorDrawable(0x7F000000));

        fixPopupWindow(mPopupWindow);
    }

    private void initButtons(String title, String[] tags, OnClickListener listener) {
        popupViewGroup = new FrameLayout(mContext);
        popupViewGroup.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT));

        popupLayout = new LinearLayout(mContext);
        popupLayout.setOrientation(LinearLayout.VERTICAL);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.BOTTOM;
        popupLayout.setLayoutParams(params);
        popupLayout.setBackgroundColor(Color.GRAY);

        LinearLayout.LayoutParams listParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
        if (!TextUtils.isEmpty(title)) {
            Button _titleView = new Button(mContext);
            _titleView.setText(title);
            _titleView.setBackgroundColor(0xFFF5F5F5);
            _titleView.setTextColor(Color.GRAY);
            _titleView.setLayoutParams(listParams);
            popupLayout.addView(_titleView);

            TextView line = new TextView(mContext);
            line.setHeight(4);
            popupLayout.addView(line);
        }
        if (tags != null) {
            for (String tag : tags) {
                Button _btn = new Button(mContext);
                _btn.setText(tag);
                _btn.setTag(tag);
                _btn.setBackgroundColor(0xFFF5F5F5);
                _btn.setTextColor(Color.BLACK);
                _btn.setLayoutParams(listParams);
                _btn.setOnClickListener(listener);
                popupLayout.addView(_btn);

                TextView line = new TextView(mContext);
                line.setHeight(2);
                popupLayout.addView(line);
            }
        }

        final Button cancelButton = new Button(mContext);
        cancelButton.setText("取消");
        cancelButton.setBackgroundColor(0xFFF5F5F5);
        cancelButton.setTextColor(Color.GRAY);

        LinearLayout.LayoutParams cancelParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
        cancelParams.topMargin = 4;
        cancelButton.setLayoutParams(cancelParams);

        // 添加按钮
        popupLayout.addView(cancelButton);
        popupViewGroup.addView(popupLayout);

        cancelButton.setOnClickListener(listener);

        popupViewGroup.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int height = popupLayout.getTop();
                int y = (int) event.getY();
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (y < height) {
                        // mPopupWindow.dismiss();
                        //解决点击阴影处无响应问题，改为点击阴影处时，主动触发cancel button onclick
                        cancelButton.performClick();
                    }
                }
                return true;
            }
        });
    }

    private void fixPopupWindow(final PopupWindow window) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            try {
                final Field fAnchor = PopupWindow.class.getDeclaredField("mAnchor");
                fAnchor.setAccessible(true);
                Field listener = PopupWindow.class.getDeclaredField("mOnScrollChangedListener");
                listener.setAccessible(true);
                final ViewTreeObserver.OnScrollChangedListener originalListener = (ViewTreeObserver.OnScrollChangedListener) listener
                    .get(window);
                ViewTreeObserver.OnScrollChangedListener newListener = new ViewTreeObserver.OnScrollChangedListener() {
                    @SuppressWarnings("unchecked")
                    @Override
                    public void onScrollChanged() {
                        try {
                            WeakReference<View> mAnchor = (WeakReference<View>) fAnchor.get(window);
                            if (mAnchor == null || mAnchor.get() == null) {
                                return;
                            } else {
                                originalListener.onScrollChanged();
                            }
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                };
                listener.set(window, newListener);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
